const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const jwt = require('jsonwebtoken')
const koaJwt = require('koa-jwt')
// const log4js = require('log4js'); // 需要引入 log4js
// const logger = require('koa-logger')


const users = require('./routes/users')
const menu = require('./routes/menu')
const roles = require('./routes/roles')
const router = require('koa-router')()
// error handler
onerror(app)
require('./config/db')
// const logger = log4js.getLogger();
// logger.level = 'debug';
// logger.debug('debug message');
const log4js = require('./utils/log4j');
const util = require('./utils/util')

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
// app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  // const start = new Date() 
  log4js.info(`get params:${JSON.stringify(ctx.request.query)}`)
  log4js.info(`post params:${JSON.stringify(ctx.request.body)}`)
  await next().catch((error)=>{
    console.log('Error Status:', error.status);  // 输出错误状态码

    // console.log(error,'223132cl')
    if(error.status === 401){
      ctx.status = 200
      ctx.body = util.fail('token认证失败',util.CODE.AUTH_ERROR)
    }else{
      throw error
    }
  })
  log4js.info('info output')
  // const ms = new Date() - start
  // console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
app.use(koaJwt({secret:'jason'}).unless({
  path:[/^\/api\/users\/login/]
}))
router.prefix('/api')


router.get('/leave/count',(ctx)=>{
  const token= ctx.request.headers.authorization.split(' ')[1]
  const palyload = jwt.verify(token, 'jason')
  // console.log(palyload,'palyload')
  ctx.body =palyload
})
router.use(users.routes(), users.allowedMethods())
router.use(menu.routes(), menu.allowedMethods())
router.use(roles.routes(), roles.allowedMethods())

app.use(router.routes(), router.allowedMethods())
// routes

// app.use(menu.routes(), menu.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
